// 云函数入口文件
const cloud = require('wx-server-sdk')
const axios = require('axios')
const doubanbook = require('doubanbook')
const cheerio = require('cheerio')

// cloud.init()
cloud.init({
  env: cloud.DYNAMIC_CURRENT_ENV
})

async function searchDouban(isbn) {
  const url = "https://search.douban.com/book/subject_search?search_text=" + isbn;
  // console.log(url)
  let searchInfo = await axios.get(url)
  // console.log(searchInfo)
  let reg = /window\.__DATA__ = "(.*)"/
  if (reg.test(searchInfo.data)) {
    // 数据解密
    let searchData = doubanbook(RegExp.$1)[0]
    // console.log(searchData)
    return searchData
  } else {
    return false
  }
}

async function getDouban(isbn) {
  const detailInfo = await searchDouban(isbn)
  if (!detailInfo) {
    return false
  }
  const detailPage = await axios.get(detailInfo.url)
  const $ = cheerio.load(detailPage.data)
  const info = $("#info").text().split('\n').map(v => v.trim()).filter(v => v)
  // console.log(info)
  // 分类
  // 价格
  // 出版社
  // 作者
  let author = info[1]
  let publisher, price
  info.forEach(v => {
    let temp = v.split(":")
    if (temp[0] === '出版社') {
      publisher = temp[1]
    } if (temp[0] === '定价') {
      price = temp[1]
    }
  })

  // 标签
  let tags = []
  $("#db-tags-section a.tag").each((i, v) => {
    tags.push({
      title: $(v).text()
    })
  })
  // console.log(tags)
  let time = await format()
  const ret = {
    tags,
    author,
    publisher,
    price,
    time,
    image: detailInfo.cover_url,
    rate: detailInfo.rating.value,
    alt: detailInfo.url,
    title: detailInfo.title,
    summary: $('#link-report .intro').text()
  }
  console.log(ret)
  return ret
}

function add0(m) { return m < 10 ? '0' + m : m }
function format() {
  // shijianchuo是整数，否则要parseInt转换
  var time = new Date()
  var y = time.getFullYear()
  var m = time.getMonth() + 1
  var d = time.getDate()
  var h = time.getHours()
  var mm = time.getMinutes()
  var s = time.getSeconds()
  return y + '-' + add0(m) + '-' + add0(d) + ' ' + add0(h) + ':' + add0(mm) + ':' + add0(s)
}

// getDouban("11102250")

// 云函数入口函数
exports.main = async (event, context) => {
  const { isbn } = event
  if (isbn) {
    return getDouban(isbn)
  } else {
    return {
      code: -1,
      msg: '请扫描正确的图书！'
    }
  }
}